package com.bt.framework.ext

import android.graphics.Paint
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.forEach
import androidx.core.view.marginEnd
import androidx.core.view.marginStart

/**
 * 获取TextView的宽度
 */
fun TextView.getViewWidth(): Float {
    return paint.measureText(text.toString()) +
            paddingStart + paddingEnd +
            marginStart + marginEnd
}

/**
 * 获取TextView的宽度
 */
fun TextView.getTextGroupWidth(view: ViewGroup): Float {
    var width = 0F
    view.forEach {
        if (it is TextView) {
            width += it.getViewWidth()
        }
    }
    return width
}

/**
 * 给TextView添加删除线删除线
 */
fun TextView.strikeThroughText() {
    paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG.inv()
}

/**
 * 取消给TextView添加删除线
 */
fun TextView.cancelStrikeThroughText() {
    paintFlags = paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
}

/**
 * 给TextView字体添加小粗
 **/
fun TextView.bold() {
    paint.isFakeBoldText = true
}

/**
 * 给TextView字体添加粗体
 **/
fun TextView.Bold() {
    typeface = Typeface.defaultFromStyle(Typeface.BOLD)
}

fun TextView.showMemCodeText(memCoed : String?) {
    text = memCoed?.let {
        var showText = StringBuilder("")
        if (it.length > 8){
            showText.append(it.substring(0, 3))
            showText.append(" ")
            showText.append(it.substring(3, 9))
            showText.append(" ")
            showText.append(it.substring(9, it.length))
        }else{
            showText.append(it.length)
        }
        showText.toString()
    }?:let { "" }
}

/**
 * 给TextView添加四周边框图片
 */
fun TextView.compoundDrawable(
    start: Int = 0,
    top: Int = 0,
    end: Int = 0,
    bottom: Int = 0
) {
    setCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom)
}

/**
 * 给TextView添加四周边框图片
 */
fun TextView.compoundDrawable(
    start: Drawable? = null,
    top: Drawable? = null,
    end: Drawable? = null,
    bottom: Drawable? = null
) {
    setCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom)
}